package mrt.cse.tempworks.initialWorksOfTeamMembers.ishara;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ${mrt.cse.gajanidu.temp.ishara}
 * Date: 1/19/12
 * Time: 12:10 PM
 * To change this template use File | Settings | File Templates.
 */
public class Sample implements Watcher{

    public static ZooKeeper zk = null;
    private CreateMode createMode = CreateMode.EPHEMERAL;
    //private Manager manager= new Manager("abd");
    //String root;

    void SyncPrimitive(String address) throws InterruptedException, KeeperException {
        if(zk == null){
            try {
                System.out.println("Starting ZK:");
                zk = new ZooKeeper(address,3000,this);
                createNodes(zk);
                getNodeInfo(zk);
                viewNodeData(zk);
                setDataToNodes(zk);
                viewNodeData(zk);

            } catch (IOException e) {
                System.out.println(e.toString());
                zk = null;
            }
        }
    }

    public void createNodes(ZooKeeper zk) throws InterruptedException, KeeperException {
        byte[] data  = {1,2};
        List<ACL> aclList = new ArrayList<ACL>();
        ACL acl = new ACL(3,new Id("ip","127.0.0.1"));

        aclList.add(acl);
        zk.create("/zoo_tiger", data, aclList, createMode);
        System.out.println("Created node");

    }

    public void getNodeInfo(ZooKeeper zk) throws InterruptedException, KeeperException {
        List<String> nodes = zk.getChildren("/", true);
        for(String node: nodes){
            System.out.println(node);
        }
    }

    public void setDataToNodes(ZooKeeper zk) throws InterruptedException, KeeperException {
        //byte[] newdata = manager.name.getBytes();
           // zk.setData("/zoo_tiger",newdata, -1);
    }

    public void viewNodeData(ZooKeeper zk) throws InterruptedException, KeeperException {
        //Stat stat;
        byte[] nodeData = zk.getData("/zoo_tiger",this,null);
        for(byte datawritten : nodeData){
            System.out.println(Byte.toString(datawritten));
        }

    }
    /*synchronized public void process(WatchedEvent event) {
        synchronized (mutex) {
            mutex.notify();
        }
    }*/

    public static void main(String[] args) throws InterruptedException, KeeperException {
        Sample sample = new Sample();
        sample.SyncPrimitive("127.0.0.1:2181");

    }


    @Override
    public void process(WatchedEvent event) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}

